package com.common.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 2008-05-01
 * @author dave
 * @version
 */
public class FileDownload extends HttpServlet {

	private static Logger log = Logger.getLogger(FileDownload.class.getName());

	private String contentType = "application/x-msdownload";
	private String enc = "utf-8";
	private String fileRoot = "";

	/**
	 * 初始化contentType，enc，fileRoot
	 */
	public void init(ServletConfig config) throws ServletException {
		String tempStr = config.getInitParameter("contentType");
		if (tempStr != null && !tempStr.equals("")) {
			contentType = tempStr;
		}
		tempStr = config.getInitParameter("enc");
		if (tempStr != null && !tempStr.equals("")) {
			enc = tempStr;
		}
		tempStr = config.getInitParameter("fileRoot");
		if (tempStr != null && !tempStr.equals("")) {
			fileRoot = tempStr;
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream servletOS = null;
		try {
			// path是指欲下载的文件的路径。
			//java.io.File.separator + "UploadFiles" + java.io.File.separator + name
			//File file = new File(request.getRealPath("/")+"/"+path);
			//File file = new File( getServletContext().getRealPath("/") + java.io.File.separator + "UploadFiles" + java.io.File.separator + path );

			String fileName = request.getParameter("fileName");
			String filePath = request.getParameter("filePath");
			String fullFilePath = "";
			if(filePath==null||filePath==""){
				fullFilePath = fileRoot + fileName; 
			}else{
				fullFilePath = filePath + fileName; //如果是linux，需要用file.sepreator;
			}
			
			log.debug("------下载文件fullFilePath="+fullFilePath);
			/*读取文件*/
			File file = new File(fullFilePath);

			/*如果文件存在*/
			if (file.exists()) {
				String filename = URLEncoder.encode(file.getName(), enc);
				response.reset();
				response.setContentType(contentType);
				response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
				int fileLength = (int) file.length();
				response.setContentLength(fileLength);
				/*如果文件长度大于0*/
				if (fileLength != 0) {
					/*创建输入流*/
					InputStream inStream = new FileInputStream(file);
					byte[] buf = new byte[4096];
					/*创建输出流*/
					servletOS = response.getOutputStream();
					int readLength;
					while (((readLength = inStream.read(buf)) != -1)) {
						servletOS.write(buf, 0, readLength);
					}
					inStream.close();
					servletOS.flush();
					servletOS.close();
				}
			} //end file exists
			else{
				response.setCharacterEncoding("UTF-8");
				response.setContentType("text/html;charset=UTF-8");
				//servletOS = response.getOutputStream();
				//servletOS.write("对不起，你要下载的文件不存在，请于管理员联系！".getBytes());
				PrintWriter  pw = response.getWriter();
				pw.print("对不起，你要下载的文件不存在，请于管理员联系！");
				log.error("------不能下载文件，因为要下载的文件不存在！------filename="+fullFilePath);
			}
		} //end try;
		catch(Exception e){
			log.error("------下载文件出错，可能是文件不存在造成的，error="+e);
			e.printStackTrace();
		}finally{
			if(servletOS!=null){
				servletOS.close();
			}
		}
	} //end method
}